package com.vichat.task;

import com.vichat.common.ffmpeg.util.FFMpegUtil;
import com.vichat.common.util.DateUtil;
import com.vichat.common.util.FileTypeUtil;
import com.vichat.common.util.NumberUtils;
import com.vichat.common.util.SystemMsgUtil;
import com.vichat.res.service.IResService;
import com.vichat.res.vo.RecFileVO;
import com.vichat.res.vo.ResFileVO;
import com.vichat.task.entity.CfgTaskParam;
import com.vichat.task.service.ITask;
import com.vichat.task.service.ITaskService;
import com.vichat.user.service.IStaticDataService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Files;
import java.util.List;
import java.util.Random;

/**
 * Created by wangluyin on 2017/9/6.
 * 数据备份
 */
@Component("MediaRecFileScanTask")
public class MediaRecFileScanTask implements ITask {
    private static transient final Logger logger = LoggerFactory.getLogger(MediaRecFileScanTask.class);

    @Autowired
    ITaskService taskService;
    @Autowired
    IStaticDataService staticDataService;
    @Autowired
    IResService resService;

    @Override
    public String doTask(long cfgTaskId) throws Exception {
        List<CfgTaskParam> cfgTaskParams = taskService.getCfgTaskParamById(cfgTaskId);
        if (cfgTaskParams != null) {
            String localPath = "";
            String removePath = "";
            String suffix = "";

            for (CfgTaskParam cfgTaskParam : cfgTaskParams) {
                if (cfgTaskParam.getParamName().equals("removePath")) {
                    removePath = cfgTaskParam.getRemark();
                }
                if (cfgTaskParam.getParamName().equals("localPath")) {
                    localPath = cfgTaskParam.getRemark();
                }
                if (cfgTaskParam.getParamName().equals("suffix")) {
                    suffix = cfgTaskParam.getRemark();
                }
            }

            if (!StringUtils.isNotBlank(localPath) || !StringUtils.isNotBlank(removePath) || !StringUtils.isNotBlank(suffix)) {
                logger.error("请检查配置");
            } else {
                MediaRecFileScanThread thread = new MediaRecFileScanThread(localPath, removePath, suffix);
                thread.start();
            }
        }
        return "success";
    }

    class MediaRecFileScanThread extends Thread {
        private String localPath;
        private String removePath;
        private String suffix;

        MediaRecFileScanThread(String localPath, String removePath, String suffix) {
            this.localPath = localPath;
            this.removePath = removePath;
            this.suffix = suffix;
        }

        public void run() {
            try {
                File fileFolder = new File(localPath);
                File[] files;
                if (fileFolder.isDirectory()) {
                    files = fileFolder.listFiles();
                } else {
                    throw new Exception(localPath + " is not Directory");
                }

                removePath += "/" +DateUtil.getToday("yyyyMMdd");
                mkdirs(removePath);

                for (File file : files) {
                    String fileName = file.getName();
                    long fileSize = file.length();
                    String fileSuffix = FileTypeUtil.getExtensionName(fileName);

                    if (suffix.contains(fileSuffix) && fileSize > 0) {//是普通文件，且文件不是空文件
                        try {
                            logger.info("filename:" + fileName);

                            RecFileVO fileVO = getFileVO(fileName);
                            fileVO.setUrl(removePath + "/" + fileName);
                            resService.addRoomResource(fileVO);

                            File dest = new File(removePath + "/" + fileName);
                            file.renameTo(dest);//迁移

                            file.deleteOnExit();
                        } catch (Exception e) {
                            e.printStackTrace();
                            logger.error("录制文件扫描进程处理出错,错误文件:" + fileName, e);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            }
        }

        private RecFileVO getFileVO(String fileName) {
            RecFileVO recFile = new RecFileVO();

            String fileNameNoEx = FileTypeUtil.getFileNameNoEx(fileName);
            String[] strs = StringUtils.splitPreserveAllTokens(fileNameNoEx, "_");//strs[0]=video;strs[1]=recd;strs[2]={rid};strs[3]={uid};strs[4]={refid};strs[5]={yyyyMMddhhmmss};
            if (strs != null && strs.length > 4) {
                long rid = NumberUtils.toLong(strs[1], -1);
                long uid = NumberUtils.toLong(strs[2], -1);
                String recdTime = strs[3];
                if (rid > 0 && uid > 0) {
                    recFile = new RecFileVO();
                    recFile.setRid(rid);
                    recFile.setUid(uid);
                    recFile.setFileName(fileName);
                    recFile.setRecdTime(recdTime);
                    recFile.setDir(DateUtil.getToday("yyyyMMdd"));
                }
            }
            return recFile;
        }

        public void mkdirs(String dirPath) {
            try {
                File dir = new File(dirPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("创建文件夹目录出错", e);
            }


        }


    }
}
